<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/2
 * Time: 10:36
 */

namespace app\api\controller;


use app\common\model\GiftRecord;
use app\common\model\Room;
use app\common\model\RoomBackground;
use app\common\model\RoomBlacklist;
use app\common\model\RoomLog;
use app\common\model\UserFollow;
use app\common\model\Users;
use app\common\service\ChatService;
use think\Db;

class Play extends User
{

    /**
     * 房间列表
     */
//    public function roomList()
//    {
//        $map['a.status'] = 1;
//        $type = input('post.type');
//        if (is_numeric($type) && !empty($type)) $map['a.type'] = $type;
//
//        $where['room_id']       = ['neq',0];
//        $where['online_status'] = 1;
//        if($type == 4){
//            $rooms = Db::name('user_extend')->where($where)->group('room_id')->cache(15)->column('room_id');
//
//            $map['a.room_id'] = ['in',$rooms];
//        }
//
//
//        $model = new Room();
//        $rows = $model->getRows($map,$this->user_id);
//        api_return(1,'获取成功',$rows);
//    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 聊天室开关公屏
     */
    public function chat()
    {
        $data = input('post.');
        $powerCode = getPowerCode($this->user_id,$data['room_id']);

        if ($powerCode == 0){
            api_return(0,'权限不足');
        }

        if($data['type'] != 'open' && $data['type'] != 'close'){
           api_return(0,'类型错误');
        }
        cache('chat'.$data['room_id'],$data['type']);
        $this->sendRoomMsg($data['room_id'],$data['type']);
        api_return(1,'操作成功');
    }

    /**
     * 进入房间
     */
    public function joinRoom()
    {

        $this->ApiLimit(1,$this->user_id);

        $param = input('post.');
        $model = new Room();

        $data = $model->joinRoom($param['room_id'],$this->user_id,trim($param['password']));



        if ($data !== false) {
            //加入一个房间前先执行退出房间操作

            $lastRoom = Db::name('user_extend')->where('user_id',$this->user_id)->cache(1)->value('room_id');

            $status = self::roomInfo($lastRoom,'status');

            if ($status == 1 && $lastRoom != $param['room_id']){
                self::outRoomFunc($this->user_id,$lastRoom);
            }

            //获取系统公告
            $data['sys_notice'] = self::getExplain('sys_notice');

            $chat = cache('chat'.$data['room_id']);

            //判断是否开启公屏
            if ($chat == 'close'){
                $data['chat'] = 0;
            }else{
                $data['chat'] = 1;
            }

            $hotValue = hotValue($data['room_id']);

            //贵族加入房间增加热度房间
            $noble_id = self::checkNoble($this->userExtra('user_id,noble_id,noble_time'));
            if ($noble_id == 5 || $noble_id == 4 || $noble_id == 3 ){
                if ($noble_id == 5){
                    $hot = 1001;
                }elseif ($noble_id == 4){
                    $hot = 501;
                }else{
                    $hot = 201;
                }

//                $in  = cache('hotRoom_'.$param['room_id'].'_'.$this->user_id);
//                if (!$in){
//                    $num = cache('noble_hot_'.$this->user_id);
//                    if ($num < 5){
//
//                        cache('noble_hot_'.$this->user_id,$num+1,todayEndTime());
//                        cache('hotRoom_'.$param['room_id'].'_'.$this->user_id,true,todayEndTime());
//                    }
//                }

            }else{
                $hot = 1;
            }
            //增加房间热度
            addHot($data['room_id'],$hot);
            $data['noble_id'] = $noble_id;
            $data['level'] = $this->userExtra('level');
            //查询当前用户是否被禁言

            $map['room_id']  = $data['room_id'];
            $map['user_id']  = $this->user_id;
            $map['status']   = 1;
            $map['end_time'] = ['>',time()];

            $data['baned'] = Db::name('room_baned')->where($map)->value('id')?true:false;
            //修改当前用户所在房间
            Db::name('user_extend')->where('user_id',$this->user_id)->update(['room_id'=>$data['room_id']]);

            //房间热度
            $data['hot'] = $hotValue+$hot;

            //通知到房间热度修改
            $this->sendRoomMsg($data['room_id'],'hotChange',$data['hot']);

            api_return(1,'获取成功',$data);
        }
        api_return(0,$model->getError());
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 退出房间
     */
    public function outRoom()
    {
        $room_id = input('post.room_id');
        if (!is_numeric($room_id)){
            api_return(0,'房间id错误');
        }
        $user_room = $this->userExtra('room_id');
        if ($user_room == $room_id){
            //用户上麦成功 或在排麦中 清除排麦数据
            $refresh = self::outRoomFunc($this->user_id,$room_id);
            if ($refresh){
                //需要刷新麦序
                $this->refreshWheat($room_id);
            }
        }

        $data['room_id'] = 0;
        self::updateUserExtend($this->user_id,$data);

        api_return(1,'退出房间成功');
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间在线用户列表
     */
    public function onlineUser()
    {

        $id  = input('post.room_id');
        if (!is_numeric($id)) api_return(0,'请输入房间id');
        $online = ChatService::getInstance()->chatroom()->queryUser($id, '500', '2');

        $array  = json_decode($online,true);

        $rows = [];

        if ($array['code'] == 200 && $array['total'] >=1){
            $users = [];
            foreach ($array['users'] as $k => $v){

                $users[] = dehashid($v['id']);

            }
            $users = implode(',',$users);
            $map = [];
            $map['a.user_id'] = ['in',$users];

//            $map['e.room_id']       = $id;
//            $map['e.online_status'] = 1;
            $model = new Users();

            $rows = $model->getItems($map,$id);

        }

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间日志
     */
    public function roomLog()
    {
        $map['room_id'] = input('post.room_id');

        if (!is_numeric($map['room_id'])) api_return(0,'房间id错误');

        $model = new RoomLog();

        $rows  = $model->getRows($map);

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间黑名单列表
     */
    public function blackList()
    {
        $map['a.room_id'] = input('post.room_id');
        if (!is_numeric($map['a.room_id'])) api_return(0,'房间id错误');

        $map['a.status'] = 1;
        $map['a.end_time'] = ['>',time()];

        $model = new RoomBlacklist();

        $rows  = $model->getRows($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间打赏列表
     */
    public function roomGift()
    {

        $map['a.room_id'] = input('post.room_id');
        if (!is_numeric($map['a.room_id'])){
            api_return(0,'参数错误');
        }
        $map['a.status']  = 1;
        $model = new GiftRecord();

        $rows = $model->giftList($map);

        $rows['total'] = $model->alias('a')->where($map)->sum('total');

        $roomInfo = $this->roomInfo($map['a.room_id']);
        if ($roomInfo['type'] == 1) {
            //电台类型的房间统计守护开通流水
            $where['room_id'] = $map['a.room_id'];
            $rows['total'] += Db::name('guard_record')->where($where)->sum('price');
        }

        api_return(1,'获取成功',$rows);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 真爱排行榜
     */
//    public function trueLove()
//    {
//
//        $map['a.status'] = 1;
//        $map['a.room_id'] = ['>',0];
//        $map['g.price'] = ['>',519];
//        $model = new GiftRecord();
//
//        $rows = $model->getTrueLove($map,$this->user_id);
//
//        api_return(1,'获取成功',$rows);
//    }

//    /**
//     * Created by xiaosong
//     * E-mail:4155433@gmail.com
//     * 守护排行榜
//     */
//    public function protect()
//    {
//        $map['a.status'] = 1;
//        $map['a.room_id'] = ['>',0];
//        $model = new GiftRecord();
//        $rows = $model->protect($map,$this->user_id);
//        api_return(1,'获取成功',$rows);
//    }

//    /**
//     * Created by xiaosong
//     * E-mail:4155433@gmail.com
//     * 获取CP排行榜
//     */
//    public function guard()
//    {
//        $time = cache('guardTime');
//        $map = [];
//
//        $id = dehashid(input('post.id'));
//        if (is_numeric($id)){
//            $map['a.guard_user'] = $id;
//        }
//
//
//        if (time()+86430 > $time){
//            $time = time() + 86430;
//            cache('guardTime',$time);
//        }
//
//        $map['a.status'] = 1;
//        $map['a.end_time'] = ['>',$time];
//
//        $model = new UserGuard();
//        $rows = $model->getRows($map);
//
//        api_return(1,'获取成功',$rows);
//
//    }

//    /**
//     * Created by xiaosong
//     * E-mail:4155433@gmail.com
//     * 获取贵族排行榜
//     */
//    public function noble()
//    {
//
//        $time = cache('nobleTime');
//        $map = [];
//
//        if (time()+30 > $time){
//            $time = time() + 30;
//            cache('nobleTime',$time);
//        }
//
//        $map['e.noble_id']   = ['>',0];
//        $map['e.noble_time'] = ['>',$time];
//
//        $model = new Users();
//
//        $rows = $model->getNoble($map);
//
//        api_return(1,'获取成功',$rows);
//
//    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 创建|修改房间
     */
    public function createRoom()
    {

        $data = request()->only(['room_name','img','cid','is_lock','password','notice','id'],'post');

        if (is_numeric($data['id'])){
            $room_id = $data['id'];
        }else{
            $extra = self::userExtra('noble_id,user_id,noble_time',$this->user_id);
            $noble_id = self::checkNoble($extra);

            if ($noble_id == 0) api_return(0,'非贵族不能创建房间');

            $map['create_user'] = $this->user_id;
            $map['status']  = 1;
            $room_id = Db::name('room')->where($map)->value('room_id');

            if ($room_id) api_return(0,'您已创建了房间,不能重复创建');

            $data['type'] = 4;
            $data['user_id'] = $this->user_id;
            $data['bg_id'] = Db::name('room_background')->where('status',1)->order('sort')->value('bg_id');
        }

        $model = new \app\common\logic\Room();

        $result = $model->saveChange($data);

        if ($result !== false){
            if (!is_numeric($data['id'])){
                $room_id = $model->getLastInsID();
                //发送系统消息给在线用户告知创建了房间
                $where['a.follow_user']   = $this->user_id;
                $where['a.status']        = 1;
                $where['e.online_status'] = 1;
                $model = new UserFollow();
                $rows  = $model->getOnline($where);
                if (!empty($rows)){
                    $nick_name = $this->userInfo('nick_name');
                    $content = sprintf('%s创建了房间[%s],快来围观吧!',$nick_name,$data['room_name']);
                    $extra['type'] = 'createRoom';
                    $extra['data'] = $room_id;
                    foreach ($rows as $k => $v){
                        $uid[] = hashid($v['user_id']);
                    }
                    self::sendUsrMsg('system',$uid,$content,$extra);
                }

            }else{ //修改房间通知到房间内部修改了内容
                $room = Db::name('room')
                    ->alias('a')
                    ->join('room_background b','b.bg_id = a.bg_id','LEFT')
                    ->join('room_category c','c.cid = a.cid','LEFT')
                    ->where('a.room_id',$data['id'])
                    ->field('a.notice,b.img as bg_img,a.room_name,a.is_lock,a.password,a.img,a.cid,c.cate_name')
                    ->find();
                $this->sendRoomMsg($data['id'],'changeRoom',$room);
            }
            api_return(1,'创建成功',['room_id'=> $room_id]);
        }
        api_return(0,$model->getError());

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 自己创建房间分类获取
     */
    public function roomCate()
    {
        $rows = Db::name('room_category')->where('status',1)->field('cid,cate_name')->select();
        api_return(1,'获取成功',$rows);
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 已创建房间和家族id返回接口
     */
    public function myCircle()
    {
        $map['user_id'] = $this->user_id;
        $map['status']  = 1;
        $map['create_user'] = $this->user_id;
        $roomInfo = Db::name('room')->field('room_id,room_name,img,type,cid,is_lock,password,notice')->where($map)->find();

        if ($roomInfo){
            $rows['room_id']  = $roomInfo['room_id'];
            $rows['roomInfo'] = $roomInfo;
            $rows['roomInfo']['cate_name'] = Db::name('room_category')->where('cid',$roomInfo['cid'])->value('cate_name');
        }else{
            $rows['room_id'] = 0;
            $rows['roomInfo']['room_name'] = '';
            $rows['roomInfo']['img'] = '';
            $rows['roomInfo']['type'] = 0;
            $rows['roomInfo']['room_id'] = 0;
            $rows['roomInfo']['cid'] = 0;
            $rows['roomInfo']['is_lock'] = 0;
            $rows['roomInfo']['password'] = '';
            $rows['roomInfo']['notice'] = '';
        }


        $where['group_user'] = $this->user_id;
        $where['type']   = 2;
        $where['status'] = 1;

        $noble = $this->userExtra('noble_id,noble_time,user_id');

        $rows['noble_id'] = self::checkNoble($noble);

        $rows['group_id'] = Db::name('chat_group')->where($where)->value('group_id')??0;

        api_return(1,'获取成功',$rows);
    }


    
    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间背景列表
     */
    public function bgList()
    {
        $rows = RoomBackground::field('bg_id,img,brief')->order('sort')->cache(3)->select();
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间礼物统计
     */
    public function giftCount()
    {
        $data = input();

        if (!is_numeric($data['room_id'])){
            api_return(0,'房间id错误');
        }
        $map['a.room_id'] = $data['room_id'];

        if ($data['keyword']){
            $map['u.nick_name|uuid'] = ['like','%'.trim($data['keyword']).'%'];
        }

        if (is_numeric(trim($data['startTime']))){
            if (is_numeric(trim($data['endTime']))){
                if (trim($data['endTime']) < trim($data['startTime'])){
                    api_return(0,'结束日期不能大于开始日期');
                }
                $map['a.create_time'] = ['between time',[intval($data['startTime']),intval($data['endTime'])]];
            }else{
                $map['a.create_time'] = ['> time',intval($data['startTime'])];
            }
        }elseif (is_numeric(trim($data['endTime']))){
            $map['a.create_time'] = ['<=',intval($data['endTime'])];
        }

        $model = new GiftRecord();

        $rows = $model->roomCount($map);
        $rows['total'] = $model->alias('a')
            ->join([
                ['users u','u.user_id = a.to_user','left'],
            ])
            ->where($map)
            ->sum('total');

        $roomInfo = $this->roomInfo($map['a.room_id']);
        if ($roomInfo['type'] == 1) {
            //电台类型的房间统计守护开通流水
            $where['room_id'] = $map['a.room_id'];
            if ($map['a.create_time']){
                $where['create_time'] = $map['a.create_time'];
            }
            $rows['total'] += Db::name('guard_record')->where($where)->sum('price');
        }

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间内用户礼物统计
     */
    public function userCount()
    {

        $data = input();

        if (!is_numeric($data['room_id'])){
            api_return(0,'房间id错误');
        }
        $map['a.room_id'] = $data['room_id'];

        if ($data['keyword']){
            $map['u.nick_name|uuid'] = ['like','%'.trim($data['keyword']).'%'];
        }

        if ($data['user_id']){
            $user_id = dehashid($data['user_id']);

            if (!is_numeric($user_id)){
                api_return(0,'用户id错误');
            }else{
                $map['to_user'] = $user_id;
            }
        }

        if   (is_numeric(trim($data['startTime']))){
            if (is_numeric(trim($data['endTime']))){
                if ($data['endTime'] < $data['startTime']){
                    api_return(0,'结束日期不能大于开始日期');
                }
                $map['a.create_time'] = ['between time',[$data['startTime'],$data['endTime']]];
            }else{
                $map['a.create_time'] = ['> time',$data['startTime']];
            }
        }elseif (is_numeric(trim($data['endTime']))){
            $map['a.create_time'] = ['<=',$data['endTime']];
        }

        $model = new GiftRecord();

        $rows = $model->userCount($map);

        api_return(1,'获取成功',$rows);
    }

    /**
     * 赠送排行榜
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function givingList()
    {

        $type = input('type');

        $time = '';
        $map  = [];
        $map['room_id'] = input('room_id');

        if (!is_numeric($map['room_id'])){
            api_return(0,'参数错误');
        }

        switch ($type){
            case 'day':
                $time = 'd';
                break;
            case 'week':
                $time = 'w';
                break;
            case 'month':
                $time = 'm';
                break;
            default:
                break;
        }

        if (input('field') == 'get'){
            $id = 'to_user';
        }else{
            $id = 'user_id';
        }

        $model = new GiftRecord();
        $rows  = $model->getList($map,$time,$id);

        api_return(1,'获取成功',$rows);

    }

}